//
// Created by 陈成 on 2020/1/6.
//

#include "MarsRover.h"

int
MarsRover::getX() const {
    return d_x;
}

int
MarsRover::getY() const {
    return d_y;
}

int
MarsRover::getDirection() const {
    return d_direction;
}

int
MarsRover::explore(MarsHighland *mh) {
    const char *commands = d_commands.c_str();

    auto i = 0;
    while (commands[i] != '\0') {
        switch (commands[i]) {
        case 'L':
            rotate(LEFT);
            break;
        case 'R':
            rotate(RIGHT);
            break;
        case 'M':
            move();
            break;
        default:
            assert(false);
            break;
        }

        i++;

        if (d_x < 0 || d_x > mh->getWidth() || d_y < 0 || d_y > mh->getHeight())
            return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

MarsRover::MarsRover(int x, int y, Direction direction) {
    d_x = x;
    d_y = y;
    d_direction = direction;
}

void
MarsRover::setCommands(const std::string &commands) {
    d_commands = commands;
}

void
MarsRover::move() {
    switch (d_direction) {
        case EAST:
            d_x += 1;
            break;
        case SOUTH:
            d_y -= 1;
            break;
        case WEST:
            d_x -=1;
            break;
        case NORTH:
            d_y += 1;
            break;
        default:
            assert(false);
            break;
    }
}

void
MarsRover::rotate(Side side) {
    int d = d_direction + side;

    if (d < EAST) d = NORTH;
    if (d > NORTH) d = EAST;

    d_direction = static_cast<Direction>(d);
}

